import {defineStore} from "pinia";
import {defineComponent, ref} from "vue";
import store from "@/store";

export const useCarStore = defineStore(
    "useCarStore",
    () => {

        let carItems = ref([])
        const totalPrice = ref(0)
        const allChecked = ref(false)

        const totalPriceFn = () => {
            const checkItem = carItems.value.filter((item) => item.checked || item.checked == true)
            totalPrice.value = checkItem.reduce((pre, cur) => pre + cur.price * cur.count, 0)
            allChecked.value = checkItem.length == carItems.value.length
            return totalPrice.value.toFixed(2);
        }
        //检查购物车是否存在不存在直接加入，否则增加商品个数
        const addCar = (goodsItem: any) => {
            let index = carItems.value.findIndex((item: any) => item.id == goodsItem.id)
            if (index == -1) {
                goodsItem.count = 1
                carItems.value.push(goodsItem)
            } else {
                carItems.value[index].count++
            }
        }

        //全选商品
        const checkAll = (isCheck: boolean) => {
            carItems.value.forEach((item: any) => {
                item.checked = isCheck
            })

        }

        // 删除购物车商品
        const deleteCar = (id: any) => {
            let index = carItems.value.findIndex((item: any) => item.id == id)
            if (index !== -1) {
                carItems.value.splice(index, 1)
            }

        }


        return {carItems, addCar, deleteCar, checkAll, totalPrice, totalPriceFn, allChecked}
    },

    {
        // 配置持久化
        persist: {
            // 调整为兼容多端的API
            storage: {
                setItem(key, value) {
                    uni.setStorageSync(key, value) // [!code warning]
                },
                getItem(key) {
                    return uni.getStorageSync(key) // [!code warning]
                },
            },
        },
    }
)